const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function connect() {
  try {
    // 连接到 MongoDB 服务器
    await client.connect();
    console.log("Connected to MongoDB");

    // 获取数据库和集合
    const db = client.db("vegetable"); // 修正：去掉 new 关键字
    const collection = db.collection("vegetable");

    // 插入文档
    const document = { name: "John", age: 30 };
    const result = await collection.insertOne(document); // 使用 async/await
    console.log("Document inserted successfully:", result);

    // 查询文档
    const foundDocument = await collection.findOne({ name: "John" });
    console.log("Found document:", foundDocument);

    // 更新文档
    const updateResult = await collection.updateOne(
      { name: "John" },
      { $set: { age: 31 } }
    );
    console.log("Update result:", updateResult);

    // 删除文档
    // const deleteResult = await collection.deleteOne({ name: "John" });
    // console.log("Delete result:", deleteResult);

  } catch (error) {
    console.error("Error connecting to MongoDB", error);
  } finally {
    // 确保在完成后关闭连接
    await client.close();
  }
}

// 调用连接函数
connect();